//
//  NewsViewController.m
//  CarUser
//
//  Created by 王森林 on 2018/11/29.
//  Copyright © 2018年 王森林. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsADCell.h"
#import "HomeCollectViewController.h"
#import "HomeMessagePageViewController.h"
#import "HomeSearchViewController.h"
#import "HomeFuntionCell.h"
#import "NewsInsuranceCell.h"
#import "NewsMaintainCell.h"
#import "NewShopCell.h"
@interface NewsViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) NSArray *imgsAry;   //顶部bar滚动
@property (strong, nonatomic) NSArray *functionAry;
@property (strong, nonatomic) NSArray *traderAry;

@property (strong, nonatomic)  UIView *titleView;
@property (strong, nonatomic) UIView *searchView;
@property (strong, nonatomic) UIButton *messageBtn;
@property (strong, nonatomic) UIButton *favoriteBtn;
@end

@implementation NewsViewController

- (BOOL )fd_prefersNavigationBarHidden{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self createNavUI];
    [self createUI];
    [self fetchDataFromNet];
    // Do any additional setup after loading the view.
}

- (void)createUI
{
    
    self.mainTableView.frame  = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-(IS_IPHONE_X?88:64));
    [self.mainTableView registerClass:[NewsADCell class] forCellReuseIdentifier:@"NewsADCell"];
    [self.mainTableView registerClass:[NewsInsuranceCell class] forCellReuseIdentifier:@"NewsInsuranceCell"];
    [self.mainTableView registerClass:[HomeFuntionCell class] forCellReuseIdentifier:@"HomeFuntionCell"];
    [self.mainTableView registerClass:[NewsMaintainCell class] forCellReuseIdentifier:@"NewsMaintainCell"];
    [self.mainTableView registerClass:[NewShopCell class] forCellReuseIdentifier:@"NewShopCell"];
//    [self.mainTableView registerClass:[HomeCommonCell class] forCellReuseIdentifier:@"HomeCommonCell"];
}


- (void)fetchDataFromNet
{
    //获取广告顶部
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"PZLXDM"],
                             @"PZLXDM":@"10"
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_28 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        NSDictionary *resultDict  = response;
        self.imgsAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
    //获取门店列表
    NSDictionary *tradersParams = @{
                             @"FKEY":[CommonMethod createMD5Key:@"NULL"],
                             @"mdtp00":@"1"
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CIRCLE_10 params:tradersParams md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        NSDictionary *resultDict  = response;
        self.traderAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
    
}

#pragma mark - UI相关
- (void)createNavUI{
    
//    self.navigationController.navigationBar.translucent = NO;
//    self.navigationController.navigationBar.shadowImage = [UIImage new];
//
//
//    CGFloat navHeight = 44;
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDWIDTH - kMarginLeft - kMarginRight, navHeight)];
//    self.navigationItem.titleView = titleView;
    if (!self.titleView) {
        self.titleView = [[UIView alloc] initWithFrame:CGRectMake(0,  IS_IPHONE_X?20:0, BOUNDWIDTH, IS_IPHONE_X?68:64)];
        [self.view addSubview:self.titleView];
    }
    
    //    titleView.backgroundColor = [UIColor redColor];
    
    
    //WithFrame:CGRectMake(0, 5, BOUNDWIDTH-kMarginLeft-kMarginRight-80, 30)
    self.searchView = [[UIView alloc]  initWithFrame:CGRectMake(20, 25, BOUNDWIDTH-kMarginLeft-kMarginRight-80, 30)];
     self.searchView.backgroundColor = [UIColor whiteColor];
     self.searchView.layer.cornerRadius =15;
     self.searchView.layer.masksToBounds = YES;
    [self.titleView addSubview: self.searchView];
    
    UIImage *searchImage = IMG(@"home_search");
    UIImageView *searchImageView = [[UIImageView alloc] initWithImage:searchImage];
    [ self.searchView addSubview:searchImageView];
    [searchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo( self.searchView.mas_left).offset(8);
        make.width.mas_equalTo(IMGWIDTH(searchImage));
        make.height.mas_equalTo(IMGHEIGHT(searchImage));
        make.centerY.mas_equalTo( self.searchView.mas_centerY);
    }];
    
    
    UITextField *searchField = [UITextField new];
    searchField.text = @"搜索品牌/车型/经销商";
    searchField.font = FONT_SIZE(12);
    searchField.textColor = Common_TextLowColor;
    searchField.delegate = self;
    [ self.searchView addSubview:searchField];
    [searchField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(searchImageView.mas_right).offset(9);
        make.right.mas_equalTo( self.searchView.mas_right).offset(-8);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo( self.searchView.mas_centerY);
    }];
    
    
    
    UIImage *favoriteImage = IMG(@"home_favorite");
     self.favoriteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ self.favoriteBtn setImage:favoriteImage forState:UIControlStateNormal];
    [ self.favoriteBtn addTarget:self action:@selector(favoriteAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview: self.favoriteBtn];
    [self.favoriteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo( self.searchView.mas_right).offset(14);
        make.width.mas_equalTo(34);
        make.height.mas_equalTo(34);
        make.centerY.mas_equalTo( self.searchView.mas_centerY);
    }];
    
    
    UIImage *messageImage = IMG(@"home_message");
    self.messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.messageBtn setImage:messageImage forState:UIControlStateNormal];
    [self.messageBtn addTarget:self action:@selector(messageAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.titleView addSubview:self.messageBtn];
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo( self.favoriteBtn.mas_right).offset(0);
        make.width.mas_equalTo(34);
        make.height.mas_equalTo(34);
        make.centerY.mas_equalTo( self.searchView.mas_centerY);
    }];
    
    
}


//#pragma mark ----UIScrollViewDelegate
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (scrollView == self.mainTableView) {
//        CGFloat y = scrollView.contentOffset.y;
//        if (y > 0) {
//            if (y - 60 > (IS_IPHONE_X ? 88 + 60: 64 + 60)) {
//                self.titleView.backgroundColor = [UIColor whiteColor];
//                self.searchView.backgroundColor = Common_Head_Color;
//                self.messageBtn.contentMode  = UIViewContentModeScaleToFill;
//                [self.messageBtn setImage:IMG(@"home_message1") forState:UIControlStateNormal];
//                self.favoriteBtn.contentMode  = UIViewContentModeScaleToFill;
//                [self.favoriteBtn setImage:IMG(@"home_favorite1") forState:UIControlStateNormal];
//
//            }else{
//                //                self.titleView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:(y - 60)/(IS_IPHONE_X ? 88 + 60: 64 + 60)];
//
//            }
//
//
//
//        }else{
//            self.titleView.backgroundColor = [UIColor clearColor];
//            self.searchView.backgroundColor = [UIColor whiteColor];
//            [self.messageBtn setImage:IMG(@"home_message") forState:UIControlStateNormal];
//            [self.favoriteBtn setImage:IMG(@"home_favorite") forState:UIControlStateNormal];
//
//            //            CGFloat sacle = fabs(y)*3/self.headerBgImgv.height + 1;
//            //            //            self.headerBgImgv.transform = CGAffineTransformTranslate(CGAffineTransformIdentity,0, 0);
//            //            self.headerBgImgv.transform = CGAffineTransformMakeScale(1.0, sacle);
//        }
//    }
//
//
//}
//进入收藏界面
- (void)favoriteAction:(id)sender
{
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    HomeCollectViewController  *control  = [[HomeCollectViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}

//进入消息界面
- (void)messageAction:(id)sender
{
    HomeMessagePageViewController *control = [[HomeMessagePageViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //失去焦点
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    HomeSearchViewController *control = [[HomeSearchViewController alloc] init];
    control.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:control animated:YES];
    
}


#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        {
            return 230.0f;
        }
            break;
        case 1:
        {
            return 120.0f;
        }
            break;
        case 2:
        {
            return 250;
        }
            break;
        case 3:
        {
            return 253.0f;
        }
            break;
        case 4:
        {
            return 183.0f;
        }
            break;
//
        default:
            return 105.0f;
            break;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        {
            
            NewsADCell *cell = (NewsADCell *)[tableView dequeueReusableCellWithIdentifier:@"NewsADCell" forIndexPath:indexPath];
            [cell setData:self.imgsAry];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 1:
        {
            HomeFuntionCell *cell = (HomeFuntionCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeFuntionCell" forIndexPath:indexPath];
            [cell setData:self.functionAry];
            cell.pushType = 2;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;

//
//            HomeServiceCell *cell = (HomeServiceCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeServiceCell" forIndexPath:indexPath];
//            //            [cell setDataAry:self.imgsAry];
//            return cell;
        }
            break;
        case 2:
        {

            NewsInsuranceCell *cell = (NewsInsuranceCell *)[tableView dequeueReusableCellWithIdentifier:@"NewsInsuranceCell" forIndexPath:indexPath];
            [cell setData:@""];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 3:
        {

            NewsMaintainCell *cell = (NewsMaintainCell *)[tableView dequeueReusableCellWithIdentifier:@"NewsMaintainCell" forIndexPath:indexPath];
            [cell setData:@""];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 4:
        {

            NewShopCell *cell = (NewShopCell *)[tableView dequeueReusableCellWithIdentifier:@"NewShopCell" forIndexPath:indexPath];
            [cell setData:self.traderAry];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
//
            
        default:
        {
//            HomeCommonCell *cell = (HomeCommonCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeCommonCell" forIndexPath:indexPath];
//            [cell setData:self.carHotAry[indexPath.row - 5]];
//            return cell;
            return nil;
            
        }
            break;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    if (indexPath.row > 4) {
//        Car_CarDetailViewController *push = [[Car_CarDetailViewController alloc]init];
//        NSDictionary  *dict = self.carHotAry[indexPath.row - 5];
//        push.SERIES_ID = [dict objectForKey:@"SALECAR_ID"];
//        [self.navigationController pushViewController:push animated:YES];
//    }
}


- (NSArray *)functionAry {
    if (!_functionAry) {
        _functionAry = @[@{@"imageName":@"ic_maintenance",@"title":@"车辆维修"},
                         @{@"imageName":@"ic_brake_fluid",@"title":@"车辆保养"},
                         @{@"imageName":@"ic_insurance",@"title":@"保险服务"},
                         @{@"imageName":@"ic_finance",@"title":@"金融服务"},
                         ];
    }
    return _functionAry;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
